package com.blindBox.back.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blindBox.back.commonResult.MsgBackToFront;
import com.blindBox.back.domain.Paper;
import com.blindBox.back.domain.Paperchosebywho;
import com.blindBox.back.domain.User;
import com.blindBox.back.mapper.UserMapper;
import com.blindBox.back.service.PaperService;
import com.blindBox.back.service.PaperchosebywhoService;
import com.blindBox.back.service.UserService;
import com.blindBox.back.utils.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Transactional
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PaperService paperService;
    @Autowired
    private PaperchosebywhoService paperchosebywhoService;
    @Autowired
    private FileUtils fileUtils;
    @Override
    public Integer getManNums() {
        return userMapper.getManNums();
    }

    @Override
    public Integer getWomanNums() {
        return userMapper.getWomanNums();
    }

    @Override
    public Integer getAllUsersNum() {
        return userMapper.getAllUsersNum();
    }

    @Override
    //封禁用户
    public MsgBackToFront banUserById(Integer u_id)
    {
        //封禁用户，并删除当前用户发布的所有纸条
        User user=new User();
        user.setBan(1);
        user.setId(u_id);
        this.updateById(user);
        //删除用户发布的纸条
        //1.查出当前用户对应的所有纸条信息
        Map<String, Object> map = new HashMap<>();
        map.put("userId",user.getId());
        List<Paper> papers = paperService.listByMap(map);
        //2.先删除每张纸条对应上传的图片
        //3.删除每张纸条的数据库记录
        for (Paper paper : papers) {
            fileUtils.delTargetFile(paper.getSelfImgs());
            paperchosebywhoService.remove(new QueryWrapper<Paperchosebywho>().eq("p_id",paper.getId()));
            paperService.removeById(paper.getId());
        }
        return new MsgBackToFront(null,MsgBackToFront.HANDLE_SUCCESS);
    }

    @Override
    //解封
    public MsgBackToFront removceBanUserById(Integer u_id) {
        //数据库记录解封
        User user=new User();
        user.setBan(0);
        user.setId(u_id);
        return this.updateById(user)?new MsgBackToFront(null,MsgBackToFront.HANDLE_SUCCESS):new MsgBackToFront(null,MsgBackToFront.DATABASE_ERROR);
    }

    @Override
    //删除用户
    public MsgBackToFront delUserById(Integer u_id) {
        banUserById(u_id);
        //删除该用户
        this.removeById(u_id);
        return new MsgBackToFront(null,MsgBackToFront.HANDLE_SUCCESS);
    }
}
